package com.ls.mianshi;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.TreeSet;

public class ArrayListAddCapacy {
    public static void main(String[] args) {
        ArrayList<Object> list = new ArrayList<>();
        getCapacity(list);
        list.add(1);
        getCapacity(list);
        TreeSet<Integer> set = new TreeSet<>();
        for (int i = 0; i < 100; i++) {
            list.add(1);
            set.add(getCapacity(list));
        }
        set.forEach(item -> {
            System.out.print(item+",");
        });

    }

    /**
     * 获得初始容量
     * @param list
     * @return
     */
    public static int getCapacity(ArrayList list){
        // java反射机制得到
        Integer length = null;
        Class c = list.getClass();
        Field data;
        try {
            data = c.getDeclaredField("elementData");
            data.setAccessible(true);
            Object[] o = (Object[]) data.get(list);
            length = o.length;
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return length;
    }

}
